package com.gifts.ui.page.common;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;


/**
 * A container class for JThumbnail
 * 
 * @author dmaung
 *
 */
public class JThumbnailPanel extends JPanel {
	
	private static final int MAX = 10;
	private int startIndex = 0;
	private int endIndex = 0;
	private int currentDisplaySize = 0;
	private int height;
	private volatile boolean exceedLimit = false;
	
	
	private boolean cancelled  = false;
	private volatile List<JThumbnailInfo> thumbnailInfos ;
	private JPanel jpanel;
	AdjustmentListener adjustmentListener ;
	private JScrollPane scrollPane;
	private JButton showMore;
	public JThumbnailPanel(int height, JButton showMorebutton) {
		this.height = height;
		jpanel = new JPanel();
		this.showMore = showMorebutton;
		scrollPane = new JScrollPane(jpanel,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setAutoscrolls(true);
		adjustmentListener = new AdjustmentListener(){
			public void adjustmentValueChanged(AdjustmentEvent e){
				e.getAdjustable().setValue(e.getAdjustable().getMaximum());
				scrollPane.getVerticalScrollBar().removeAdjustmentListener(adjustmentListener);
			}
		};
	
		showMore.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(exceedLimit){
					showMore.setVisible(false);
				} else {
					showMore.setVisible(true);
				}
				int nextSize = currentDisplaySize+MAX;
				System.out.println("currentDisplaySize:" +  nextSize);
				System.out.println("thumbnailSize:" +  thumbnailInfos.size());
				startIndex = endIndex;
				endIndex +=MAX;
				if(endIndex> thumbnailInfos.size()) {
					endIndex = thumbnailInfos.size();
				}
				System.out.println("StartIndex=" + startIndex);
				System.out.println("EndIndex="+ endIndex);
				loadIconsInBackground(startIndex, endIndex);
				int nextIndex = endIndex + MAX;
				if(nextIndex > thumbnailInfos.size()) {
					exceedLimit = true;
				} else {
					showMore.setEnabled(false);
				}
				
				
				
			}
			
		});
		

		
		scrollPane.setPreferredSize(new Dimension(780,height));
		jpanel.setPreferredSize(new Dimension(780,height-10));
		
		FlowLayout gridLayout = new FlowLayout();
		gridLayout.setHgap(30);
		//gridLayout.setVgap(10);
		gridLayout.setAlignment(FlowLayout.LEFT);
	
		jpanel.setLayout(gridLayout);
		thumbnailInfos = new ArrayList<JThumbnailInfo>();
		setLayout(new FlowLayout());
	
		add(scrollPane);
		
	}
	
	public synchronized void cancel() {
		if(loadImages != null) {
			loadImages.cancelled();
			loadImages.cancel(true);
		}
		this.startIndex = 0;
		this.endIndex = 0;
		this.exceedLimit = false;
	}
	
	public void removeAll() {
	
	
		jpanel.removeAll();
		thumbnailInfos.clear();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
		
		
	}
	private boolean reset = false;
	MySwingWorker  loadImages;
	
	
	
	public void loadIconsInBackground() {
		startIndex = 0;
		endIndex = 0;
		int size = thumbnailInfos.size();
		System.out.println("SIZ:E" + size);
		if(size <= MAX) {
			
			loadIconsInBackground(0, size);
			showMore.setVisible(false);
			
		} else {
			loadIconsInBackground(0, 10);
			showMore.setVisible(true);
			showMore.setEnabled(false);
		}
		currentDisplaySize = 10;
		exceedLimit = false;
		
		jpanel.setPreferredSize(new Dimension(800,height-10));
		
		
		
		
		
	}
	public void loadIconsInBackground(int startIndex , int endIndex) {
			
			this.startIndex  = startIndex;
			this.endIndex = endIndex;
			
			loadImages  =  new  MySwingWorker();
			loadImages.execute();
		
			if(endIndex > MAX) {
				scrollPane.getVerticalScrollBar().removeAdjustmentListener(adjustmentListener);
				int size = endIndex;
				double row  = (double) size/5;
				int rowSize = (int)Math.ceil(row);
				System.out.println("rowSize:" + rowSize);
				jpanel.setPreferredSize(new Dimension(780,((height/2)+2)*rowSize));
				scrollPane.getVerticalScrollBar().addAdjustmentListener(adjustmentListener);
			}
			
			
	
		
	}
	
	
	  /**
     * SwingWorker class that loads the images a background thread and calls publish
     * when a new one is ready to be displayed.
     *
     * We use Void as the first SwingWroker param as we do not need to return
     * anything from doInBackground().
     */
	
	private class  MySwingWorker extends SwingWorker<Void, JThumbnail> {
	
		private volatile boolean cancelled = false;
		
		public void cancelled() {
			 cancelled = true;
		}
		
        /**
         * Creates full size and thumbnail versions of the target image files.
         */
        @Override
        protected Void doInBackground() throws Exception {
        

       	
        	
            for (int i = startIndex; i <  endIndex; i++) {
                JThumbnail thumbnail = null;
                JThumbnailInfo thumbnailInfo = thumbnailInfos.get(i);
               // System.out.println("Displaying:" + i);
                String url = thumbnailInfo.getUrl();
                String text1 = thumbnailInfo.getText1();
                String text2 = thumbnailInfo.getText2();
                String text3 = thumbnailInfo.getText3();
                MouseListener mouseListener = thumbnailInfo.getMouseListener();
                
                if(text3 != null) {
                	thumbnail = new JThumbnail(url, text1, text2, text3);
                } else if(text2 != null) {
                	thumbnail = new  JThumbnail(url, text1, text2);
                } else if(text1 != null) {
                	thumbnail = new JThumbnail(url,text1);
                }
                
                thumbnail.addMouseListener(mouseListener);
                
                
               
                publish(thumbnail);
            }
            // unfortunately we must return something, and only null is valid to
            // return when the return type is void.
            return null;
        }
         
        /**
         * Process all loaded images.
         */
        @Override
        protected void process(List<JThumbnail> chunks) {
        	 if(cancelled) {
             
 				
 				return ;
             }
        	
            for (JThumbnail thumbnail : chunks) {
            	
               
                // add the new button BEFORE the last glue
                // this centers the buttons in the toolbar
               jpanel.add(thumbnail);
               
               
            }
            
           jpanel.revalidate();
            repaint();
            revalidate();
        }
        
        protected void done() {
        	repaint();
        	revalidate();
        	showMore.setEnabled(true);
        	//thumbnailInfos.clear();
        	super.done();
        }
    }
    	
	
     
    /**
     * Creates an ImageIcon if the path is valid.
     * @param String - resource path
     * @param String - description of the file
     */
    protected ImageIcon createImageIcon(String path,
            String description) {
        java.net.URL imgURL;
		try {
			imgURL = new URL(path);
			  if (imgURL != null) {
		            return new ImageIcon(imgURL, description);
		        } else {
		            System.err.println("Couldn't find file: " + path);
		            return null;
		        }
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
      
    }
     
   
   
	
	
	public void  addJThumbnail(MouseListener mouseListener, String url, String text1) {
		thumbnailInfos.add(new JThumbnailInfo(mouseListener,url, text1));
		
		
	}
	
	public void addJThumnail(MouseListener mouseListener, String url, String text1, String text2) {
		thumbnailInfos.add(new JThumbnailInfo(mouseListener, url, text1,text2));
		
	}
	
	public void addJThumbnail(MouseListener mouseListener,String url, String text1, String text2, String text3) {
		thumbnailInfos.add(new JThumbnailInfo(mouseListener, url, text1,text2,text3));
	}
	
	
	
	
	
	
	
	
	
	
	

}
